package com.engine.jucailinkq.attendance.workflow.action.askforleave;

import com.engine.jucailinkq.attendance.enums.AccountingUnitEnum;
import com.engine.jucailinkq.common.util.CommonUtil;
import com.engine.jucailinkq.common.util.DbTools;
import com.engine.jucailinkq.common.util.Utils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: sy
 * @Description: 批量请假-提交节点附加操作
 * @Date: 2024/6/28
 **/
@Slf4j
public class BatchAskForLeaveWorkFlowSubmitAction implements Action {
    @Override
    public String execute(RequestInfo requestInfo) {
        String requestid = requestInfo.getRequestid();
        int billid = requestInfo.getRequestManager().getBillid();
        log.info("billid : [{}]",billid);
        try {
            // 流程表单主表数据
            HashMap<String, String> mainTableData = CommonUtil.getMainTableInfo(requestInfo);
            log.info("mainTableData : [{}]", mainTableData);
            // 流程表单明细表1数据
            List<Map<String, String>> detailTableData = CommonUtil.getDetailTableInfo(requestInfo, 0);
            log.info("detailTableData : [{}]", detailTableData);

            String detail2TableName = requestInfo.getDetailTableInfo().getDetailTable()[1].getTableDBName();
            log.info("detail2TableName : [{}]", detail2TableName);
            //第一笔开始时间
            String firstStartDate = detailTableData.get(0).get("ksrq");

            List<Map<String, Object>> detailTable2 = Lists.newArrayList();

            Map<String, Object> holidayBalanceMap = new HashMap<>();
            //需要校验假期额度的假期类型
            List<String> checkAmountJqIdList = CommonUtil.getJqInfoWithAmount();
            //根据明细表1，根据请假类型分组，对于需要校验余额的遍历生成明细表2
            Map<String, List<Map<String, String>>> detail1TabDataGroupByJqlx = detailTableData.stream().collect(Collectors.groupingBy(e -> Util.null2String(e.get("qjlx"))));
            for(Map.Entry<String,List<Map<String,String>>> entry : detail1TabDataGroupByJqlx.entrySet()) {
                if (checkAmountJqIdList.contains(entry.getKey())) {
                    String sql = "select id,jqid,sxrq,ktsc,yxsc,wxsc,yqsxrq,ztsc from uf_jcl_kq_jqye where jqid=? and sxrq<=? and yqsxrq>=? order by sxrq";
                    List<Map<String, Object>> holidayBalanceList = DbTools.getSqlToList(sql, entry.getKey(), firstStartDate, firstStartDate);
                    if (holidayBalanceList.size() > 0) {
                        holidayBalanceMap.putAll(holidayBalanceList.stream().collect(Collectors.toMap(e -> e.get("id").toString(), e -> e)));
                    }
                    sql = "select id,mc,hsdw,hsl,jcbyxsyqjb,yxsydjb,qzsyyxjb  from uf_jcl_kq_kqxm  where id=?";
                    Map<String, Object> holidayItem = DbTools.getSqlToMap(sql, entry.getKey());
                    //假期核算单位
                    String hsdw = Util.null2String(holidayItem.get("hsdw"));
                    //遍历生成明细表2
                    for (Map<String, String> detailData : entry.getValue()) {
                        String jqyeInfoStr = Util.null2String(detailData.get("jqye"));
                        List<String> jqyeInfoList = Arrays.asList(jqyeInfoStr.split(","));
                        for (String jqyeInfo : jqyeInfoList) {
                            Map<String, Object> detail2Map = Maps.newHashMap();
                            detail2Map.put("glmxid", detailData.get("id"));
                            detail2Map.put("jqye", jqyeInfo.split("_")[0]);
                            detail2Map.put("mainid", mainTableData.get("id"));
                            detail2Map.put("glrq", detailData.get("ksrq"));
                            if (hsdw.equals(AccountingUnitEnum.DAY.getKey())) {
                                detail2Map.put("sysc", Utils.divide(Double.parseDouble(jqyeInfo.split("_")[1]), 8));
                            } else {
                                detail2Map.put("sysc", jqyeInfo.split("_")[1]);
                            }
                            detailTable2.add(detail2Map);
                        }
                    }
                }
            }
            //明细表2有数据时，更新明细表2入库，并且更新假期余额表
            //更新流程明细表2
            String delteSql = "delete from " + detail2TableName + " where mainid=?";
            DbTools.update(delteSql, billid);
            if (detailTable2.size() > 0 && !CommonUtil.insertBatch(detailTable2, detail2TableName)) {
                //更新流程明细表2失败
                String message = "更新流程明细表2失败";
                log.error(message);
                requestInfo.getRequestManager().setMessageid("11111" + requestid + "22222");
                requestInfo.getRequestManager().setMessagecontent(message);
                return Action.FAILURE_AND_CONTINUE;
            }
            //更新假期余额在途时长
            Map<String, Object> balanceMap = Maps.newHashMap();
            for (Map<String, Object> data : detailTable2) {
                String jqye = Util.null2String(data.get("jqye"));
                double sysc = Double.valueOf(data.get("sysc").toString());
                double havedSysc = balanceMap.get(jqye) == null ? 0 : Double.valueOf(balanceMap.get(jqye).toString());
                sysc = Utils.add(sysc, havedSysc);
                balanceMap.put(jqye, sysc);
            }
            log.info("balanceMap : [{}]",balanceMap);
            for (Map.Entry<String, Object> entry : balanceMap.entrySet()) {
                String id = entry.getKey();
                double ztsc = Double.valueOf(entry.getValue().toString());
                Map<String, Object> map = (Map<String, Object>) holidayBalanceMap.get(id);

                double havedztsc = Util.null2String(map.get("ztsc")).equals("") ? 0 : Double.valueOf(map.get("ztsc").toString());
                double havedwxsc = Util.null2String(map.get("wxsc")).equals("") ? 0 : Double.valueOf(map.get("wxsc").toString());

                double updatedztsc = Utils.add(havedztsc, ztsc);
                double updatedwxsc = Utils.subtract(havedwxsc, ztsc);

                String updateSql = "update uf_jcl_kq_jqye set wxsc=?,ztsc=? where id=?";
                if (!DbTools.update(updateSql, updatedwxsc, updatedztsc, id)) {
                    //更新假期余额失败
                    String message = "更新假期余额失败";
                    log.error(message);
                    requestInfo.getRequestManager().setMessageid("11111" + requestid + "22222");
                    requestInfo.getRequestManager().setMessagecontent(message);
                    return Action.FAILURE_AND_CONTINUE;
                }
            }
            ////////////////////////////


        }catch (Exception e){
            log.error("BatchAskForLeaveWorkFlowSubmitAction error : [{}]",e);
            return Action.FAILURE_AND_CONTINUE;
        }

        return Action.SUCCESS;
    }
}
